package zb.md2html.gen;

import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;

import com.jfinal.kit.PathKit;

import cn.hutool.core.util.StrUtil;
import jodd.io.FileUtil;
import jodd.io.findfile.FindFile;
import jodd.template.MapTemplateParser;
import kits.my.BufferKit;
import lombok.val;
import lombok.extern.slf4j.Slf4j;
import zb.md2html.api.IHtml;
import zb.md2html.entity.Table;
import zb.md2html.type.MdTableType;

@Slf4j
public class ErrorCode extends ZbBase implements IHtml{
	private final String fileCodes = PathKit.getRootClassPath() + "/code/";

	@Override
	public String getApiContent() {
		val sb = new BufferKit();
		sb.append("<h1 id='错误代码'>错误代码</h1>");
		FindFile.create().searchPath(fileCodes).findAll().forEach(file -> {
			String mainName = cn.hutool.core.io.FileUtil.mainName(file);
			log.info("错误代码:"+mainName);
			try {
				val lines = Arrays.asList(FileUtil.readLines(file));
				val mdTable = getMdTable(MdTableType.代码, lines);
				val formatTable = this.formatTable(mdTable);
				sb.append("<h2 id='{}'>{}</h2>",mainName,mainName);
				sb.append(formatTable);
				
			} catch (IOException e) {
				e.printStackTrace();
			}
		});
		return sb.toString();
	}
	
	private String formatTable(Table table) throws IOException {
		val sb = new BufferKit();
		table.getTds().forEach(td -> {
			String tdStr = StrUtil.format(tdResponse, td.getParam1(),td.getParam2());
			sb.append(tdStr);
		});
		val params = new HashMap<String,String>();
		params.put("tr", StrUtil.format(trResponse, "返回码","描述"));
		params.put("tds", sb.toString());
		return new MapTemplateParser().of(params).parse(FileUtil.readString(tableTemplate));
	}

	public static void main(String[] args) {
		val html = new ErrorCode().getApiContent();
		System.out.println(html);
	}
}
